<template>
<section class="personnel-list">
  <!-- start form search -->
  <el-form :inline="true" :model="formInline" label-width="80px" size="small" class="search-form" label-suffix="：">
    <el-form-item label="名称">
      <el-input v-model="formInline.name" placeholder="请输入单位名称" style="width:200px;"></el-input>
    </el-form-item>
    <el-form-item label="地址">
      <el-input v-model="formInline.location" placeholder="请输入地址" style="width:200px;"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="clickFormSearch">查询</el-button>
      <el-button icon="el-icon-plus" type="primary" plain @click="clickAdd">新增单位</el-button>
    </el-form-item>
  </el-form>
  <!-- end form search -->
  <!-- start btn group -->
  <el-row class="table-control">
    <el-col :span="18">
<!--      <el-button icon="el-icon-plus" size="small" type="primary" plain @click="clickAdd">新增职员</el-button>-->
    </el-col>
    <el-col :span="6"></el-col>
  </el-row>
  <!-- end btn group -->
  <!-- start table -->
  <article class="table-data">
    <el-table :data="tableData" border style="width: 100%" :fit="true">
<!--      <el-table-column prop="id" label="id" ></el-table-column>-->
      <el-table-column prop="name" label="名称" ></el-table-column>
      <el-table-column prop="location" label="地址"  ></el-table-column>
      <el-table-column prop="field" label="领域">
        <template slot-scope="scope">
          {{ fieldFormatter(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="scale" label="规模" ></el-table-column>
      <el-table-column prop="profile" label="简介"></el-table-column>
      <el-table-column prop="createTime" label="申请时间">
        <template slot-scope="scope">
          {{ displayDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间">
        <template slot-scope="scope">
          {{ displayDate(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" >
        <template slot-scope="scope">
          <el-tag effect="dark" v-if="scope.row.status === 0" type="info" size="mini">{{scope.row.status | changeToText1}}</el-tag>
          <el-tag effect="dark" v-else-if="scope.row.status === 1" type="danger" size="mini">{{scope.row.status | changeToText1}}</el-tag>
          <el-tag effect="dark" v-else-if="scope.row.status === 2" type="success" size="mini">{{scope.row.status | changeToText1}}</el-tag>
          <el-tag effect="dark" v-else-if="scope.row.status === 3" type="warning" size="mini">{{scope.row.status | changeToText1}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150"  fixed="right">
        <template slot-scope="scope">
          <el-button type="danger" @click="clickDelete(scope.row)" size="mini" plain icon="el-icon-delete" circle title="删除"></el-button>
          <el-button size="mini" @click="clickEdit(scope.row)" circle icon="el-icon-edit" title="编辑"></el-button>
          <el-button size="mini" @click="clickView(scope.row)" circle icon="el-icon-view" title="审核"></el-button>

        </template>
      </el-table-column>
    </el-table>
  </article>
  <!-- end table -->
  <!-- start pagination -->
  <el-pagination :current-page="1" :page-sizes="[10, 20, 30, 40]" :page-size="1" layout="total, sizes, prev, pager, next, jumper" :total="2" class="table-pagination">
  </el-pagination>
  <!-- end pagination -->
  
  <!-- 编辑对话框 -->
  <el-dialog :title="dialogType === 'add' ? '新增单位' : '编辑单位'" :visible.sync="modalAdd" width="600px">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="关联企业" prop="recruitUnitId">
        <el-select 
          v-model="ruleForm.recruitUnitId" 
          placeholder="请选择关联企业"
          style="width: 100%">
          <el-option
            v-for="item in recruitUnitOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入单位名称"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="location">
        <el-input v-model="ruleForm.location" placeholder="请输入地址"></el-input>
      </el-form-item>
      <el-form-item label="领域" prop="field">
        <el-select v-model="ruleForm.field" placeholder="请选择领域">
          <el-option
            v-for="item in fieldOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="规模" prop="scale">
        <el-input v-model="ruleForm.scale" placeholder="请输入规模"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="profile">
        <el-input type="textarea" v-model="ruleForm.profile" placeholder="请输入简介"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="modalAdd = false">取 消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
    </div>
  </el-dialog>

  <!-- 审核抽屉 -->
  <el-drawer
          title=""
          :visible.sync="drawer"
          direction="rtl"
          style="margin-left: 10px;">
    <h2 class="single-title">企业信息</h2>
    <el-form ref="formInfo" :model="formInfo" style="margin-left: 30px;">

      <div style="text-align: center; margin-bottom: 10px">
        <img width="80px" height="80px" style="border-radius: 40px" :src="formInfo.unitImageUrl">
        <div style="margin: 10px">
          <div>
            <p style="color: #20a0ff; font-size: 14px" v-if="formInfo.status == 2">已认证</p>
            <p style="color: #20a0ff; font-size: 14px" v-if="formInfo.status == 1">审核中</p>
            <p style="color: red; font-size: 14px" v-if="formInfo.status == 3">未认证</p>
            <p style="color: red; font-size: 14px" v-if="formInfo.status == 4">封禁</p>
          </div>
        </div>
      </div>

      <div class="form-item">
        <el-form-item label="名称" prop="name">
          {{formInfo.name}}
        </el-form-item>
      </div>
      <div class="form-item">
        <el-form-item label="地址" prop="location">
          {{formInfo.location}}
        </el-form-item>
      </div>
      <div class="form-item">
        <el-form-item label="领域" prop="field">
          {{fieldFormatter(formInfo)}}
        </el-form-item>
      </div>
      <div class="form-item">
        <el-form-item label="规模" prop="scale">
          {{formInfo.scale}}
        </el-form-item>
      </div>
      <div class="form-item">
        <el-form-item label="简介" prop="profile">
          {{formInfo.profile}}
        </el-form-item>
      </div>
      <div class="form-item">
        <el-form-item label="营业执照" prop="profile">
          <div class="demo-image__preview">
            <el-image
                    style="width: 100px; height: 100px"

                    :src="require('../../../source/zhizhao.jpeg')"
                    :preview-src-list="srcList">
            </el-image>
          </div>
        </el-form-item>
      </div>
      <div style="text-align: center">
        <el-button type="info" round v-if="formInfo.status == 0 || formInfo.status == 1 || formInfo.status == 3" @click="clickShenhe(0)" >不通过</el-button>
        <el-button type="success" round v-if="formInfo.status == 0 || formInfo.status == 1 || formInfo.status == 3" @click="clickShenhe(2)">通过</el-button>
        <el-button type="danger" round v-if="formInfo.status == 2" @click="clickShenhe(4)">封禁</el-button>
      </div>
    </el-form>
  </el-drawer>
</section>
</template>

<script>
import axios from 'axios'  // 确保正确导入
export default {
  name: 'PersonnelList', //人员管理
  data() {
    return {
      // 领域选项
      fieldOptions: [
        { value: 1, label: '餐饮' },
        { value: 2, label: '景点' },
        { value: 3, label: '外卖' },
        { value: 4, label: '其它' }
      ],
      modalAdd: false,
      pageCurrent: 1,//默认页码
      pageSize: 50,//默认页的尺寸
      count: 0,//数据的总记录数
      loadingDept:false,
      deptOptions:[],
      roleOptions:[],
      formInline: {
        name: '',
        location: '',
      },
      recruitUnitOptions: [], // 企业选项列表
      ruleForm: {
        id: '',              
        name: '',            
        location: '',        
        field: '',          
        scale: '',          
        profile: '',        
        recruitUnitId: '',   // 关联企业ID
      },
      rules: {
        name: [{
          required: true,
          message: '请输入单位名称',
          trigger: 'blur'
        }],
        location: [{
          required: true,
          message: '请输入地址',
          trigger: 'blur'
        }],
        field: [{
          required: true,
          message: '请选择领域',
          trigger: 'change'
        }],
        scale: [{
          required: true,
          message: '请输入规模',
          trigger: 'blur'
        }],
        profile: [{
          required: true,
          message: '请输入简介',
          trigger: 'blur'
        }],
        recruitUnitId: [{
          required: true,
          message: '请选择关联企业',
          trigger: 'change'
        }],
      },
      tableData: [],
      drawer: false,//审核抽屉
      formInfo: {},//单位信息
      url: 'https://jianzhi-backet.oss-cn-shenzhen.aliyuncs.com/recruitUnit/0/zhizhao.jpeg',
      srcList: [
        'https://jianzhi-backet.oss-cn-shenzhen.aliyuncs.com/recruitUnit/0/zhizhao.jpeg'
      ]
    }
  },
  created() {
    // 添加请求拦截器，检查请求是否正确发送
    this.$axios.interceptors.request.use(config => {
      console.log('发送请求:', config);
      return config;
    });
  },
  methods: {
    // 领域格式化显示
    fieldFormatter(row) {
      // 如果是编辑时的数据（已经是数字）
      if (typeof row.field === 'number') {
        const field = this.fieldOptions.find(item => item.value === row.field);
        return field ? field.label : '';
      }
      // 如果是从后端获取的数据（是字符串）
      return row.field || '';
    },
    roleFormatter(row){
        var a = this.roleOptions
        var role = a.filter((p)=>{
           return p.value == row.roleId;
        });
        return role[0].label;
    },
    deptFormatter(row){
        var a = this.deptOptions
        console.log('000000000000'+JSON.stringify(row));
        var dept = a.filter((p)=>{
           return p.value == row.deptId;
        });
        return dept[0].label;
    },
    sexFormatter(row) {
      console.log(row.sex+'33333');
      if(row.sex==0){
        return '男';
      }else{
        return '女';
      }
    },
    clickAdd() {
      this.dialogType = "add";
      this.modalAdd = true;
      this.getRecruitUnitList(); // 获取企业列表
    },
    addPerson(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const submitData = {
            ...this.ruleForm,
            field: `{${this.ruleForm.field}}`,
            createTime: this.formatDate(this.ruleForm.createTime),
            updateTime: this.formatDate(this.ruleForm.updateTime)
          };
          
          this.$axios.post("/recruitUnit/add", submitData).then((res) => {
            if (res.code == 200) {
              this.$message.success("添加成功");
              this.initForm();
              this.queryList({
                pageSize: this.pageSize,
                pageCurrent: this.pageCurrent
              });
              this.modalAdd = false;
            } else {
              this.$message.error(res.msg || "添加失败");
            }
          });
        } else {
          return false;
        }
      });
    },

     clickEdit(params) {
      console.log("点击编辑按钮");
      console.log("编辑传入的参数", params);
      this.dialogType = "edit";
      this.modalAdd = true;
      this.getRecruitUnitList(); // 获取企业列表
      // 将字符串 {1} 转换为数字 1
      const fieldValue = params.field ? parseInt(params.field.replace(/[{}]/g, '')) : '';
      const editData = {
        ...params,
        field: fieldValue
      };
      Object.assign(this.ruleForm, editData);
      console.log("ruleForm数据", this.ruleForm);
    },

     updatePerson(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const submitData = {
            ...this.ruleForm,
            field: `{${this.ruleForm.field}}`,
            createTime: this.formatDate(this.ruleForm.createTime),
            updateTime: this.formatDate(this.ruleForm.updateTime)
          };
          
          this.$axios.post("/recruitUnit/edit", submitData).then((res) => {
            if (res.code == 200) {
              this.$message.success("更新成功");
              this.initForm();
              this.queryList({
                pageSize: this.pageSize,
                pageCurrent: this.pageCurrent
              });
              this.modalAdd = false;
            } else {
              this.$message.error(res.msg || "更新失败");
            }
          });
        } else {
          return false;
        }
      });
    },

    //重置
    initForm() {
      this.modalAdd = false;
      this.resetEdit();
    },
    resetEdit(){
      return (this.ruleForm = {
        id: '',             
        name: '',
        location: '',
        field: '',
        scale: '',
        profile: '',
        recruitUnitId: '',  // 重置关联企业ID
      });
    },

    //搜索
    clickFormSearch() {
      this.queryList({
        pageSize: this.pageSize,
        pageCurrent: this.pageCurrent,
        name: this.formInline.name,
        location: this.formInline.location,
      });
    },
    queryList(data) {
      this.$axios.post("/recruitUnit/list", data).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.records;
          this.count = res.data.total;
          this.pageCurrent = res.data.current;
        } else {
          this.$message.error("查询失败!");
        }
      });
    },

    clickDelete(row) {
      this.$confirm('此操作将永久删除此项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          console.log(row);
          this.deletePerson(row);
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    deletePerson(data){
        this.$axios.delete("/recruitUnit/delete/" + data.id).then((res) => {
        if (res.code == 200) {
          this.$message.success("删除成功");
          if (
            (this.pageCurrent * this.pageSize - this.count) % this.pageSize ==
            this.pageSize - 1
          ) {
            this.pageCurrent -= 1;
          }
          this.queryList({
            pageSize: this.pageSize,
            pageCurrent: this.pageCurrent,
          });
        }else{
          this.$message.error(res.msg || "删除失败");
        }
      });
    },


    queryDept(){
      var list = [];//接收返回的数据
      var states = [];
      console.log("222222222")
      let a ={};
          this.loadingDept = true;//从远程获取数据
          this.$axios.post("/proDept/list",a).then((res) => {
            if (res.code == 200) {



              states = res.data.records;

              list = states.map(item => {
                console.log('33333344'+item.name);

                return {
                   value: `${item.id}`,
                    label: `${item.name}` };
              });
              setTimeout(() => {
                this.loadingDept = false;
                this.deptOptions = list;
              }, 200);
              console.log(list);

            }
          });


    },

    queryRole(params){
      console.log('ppppp'+params);
      if(params == null){
        params={}
      }
      var list = [];//接收返回的数据
      var states = [];
       console.log("222222222")
      // let a ={};
          //this.loadingDept = true;//从远程获取数据
          this.$axios.post("/proRole/list",params).then((res) => {
            if (res.code == 200) {
              states = res.data.records;
              list = states.map(item => {
                return {
                   value: `${item.id}`,
                    label: `${item.name}` };
              });
              setTimeout(() => {
                //this.loadingDept = false;
                this.roleOptions = list;
              }, 200);

            }
          });
    },

    //点击审核
    clickView(val){
console.log('val' ,val )
      this.drawer = true;

      this.formInfo = val
    },
    //点击审核通过
    clickShenhe(status){
      this.$confirm("是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
          this.$axios.post("/recruitUnit/edit",{id:this.formInfo.id,status:status}).then(res=>{
            if (res.code == 200){
              this.$message.success("操作成功")
              this.drawer = false;
            }
          })
        }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });

    },
    submitForm(formName) {
        if (this.dialogType === 'add') {
            this.addPerson(formName);
        } else {
            this.updatePerson(formName);
        }
    },
    // 日期格式化
    formatDate(date) {
      if (!date) return '';
      // 转换为后端需要的格式 yyyy-MM-ddTHH:mm:ss.SSSZ
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      const seconds = String(d.getSeconds()).padStart(2, '0');
      const timezone = '+0800'; // 中国时区
      
      return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.000${timezone}`;
    },
    // 显示格式化（用于表格显示）
    displayDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      const seconds = String(d.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 获取企业列表
    getRecruitUnitList() {
      this.$axios.get('/recruitUnit/listByHrId').then(res => {
        if (res.code === 200) {
          this.recruitUnitOptions = res.data.map(item => ({
            value: item.id,
            label: item.name
          }));
        } else {
          this.$message.error('获取企业列表失败');
        }
      });
    },
  },


  filters: {
    changeToText1(value) {
      if (value == '0')
        return '未通过审核'
      else if (value == '1') {
        return '待审核'
      }else if (value == '2') {
        return '审核通过'
      }else if (value == '3') {
        return '不存在的情况'
      }
    },

  },
  mounted() {
    this.queryList({
      pageSize: this.pageSize,
      pageCurrent: this.pageCurrent,
    });
    this.queryDept();
    this.queryRole();

  },

};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">

.personnel-list {}

</style>
